Jump Statements. ˆ The break statement exits a for or while loop completely.
|
|
- Richard Lloyd
- 5 years ago
- Views:
Transcription
1 Jump Statements ˆ The break statement exits a for or while loop completely. ˆ No longer in the loop. ˆ Aka early termination. ˆ To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. ˆ Still in the loop. ˆ Statements in the loop after the break statement do not be executed. ˆ In practice, the break and continue statements should reside in if statements. Zheng-Liang Lu 125 / 182
2 Example: PRIMES Problem ˆ Let x be any positive integer larger than 2 as input. ˆ Then x is a prime number if y {2, 3,..., x 1}, y is not a divisor of x, denoted by y x. ˆ In other words, x is called a composite number if y {2, 3,..., x 1}, y x. ˆ Now write a program which determines if x is a prime number. Zheng-Liang Lu 126 / 182
3 1 clear; clc; 2 3 x = input('enter a positive integer? '); 4 isprime = true; % a flag, true if the number is prime 5 for i = 2 : sqrt(x) 6 if mod(x, i) == 0 7 isprime = false; 8 break; 9 end 10 end if isprime 13 disp([num2str(x) ' is a prime number.']); 14 else 15 disp([num2str(x) ' is a composite number.']); 16 end ˆ Note that this is a brute-force algorithm. 1 1 Manindra Agrawal, Neeraj Kayal, Nitin Saxena (2002) proves that PRIMES is in P. Zheng-Liang Lu 127 / 182
4 Equivalence: for and while Loops ˆ Redo the compounding problem by using a for loop. 1 clear; clc; 2 3 curr = 100; 4 goal = 200; 5 r = 0.01; 6 7 for n = 1 : inf 8 curr = curr * (1 + r); 9 if curr >= goal 10 break; 11 end 12 end 13 n Zheng-Liang Lu 128 / 182
5 Exercise: Number Guessing ˆ Let x be the input from the player. ˆ Generate a secret number l s u. ˆ For convenience, set l = 1 and u = 100. ˆ The program could be organized as follows: 1. For each round, display the feasible range. For example, (1, 100) for the very first turn. 2. Check if x == s. If true, then the player wins and the program ends. 3. If not, update (shrink) the feasible range accordingly. 4. Then go step 2 until l == u (lose). Zheng-Liang Lu 129 / 182
6 1 clear; clc; 2 3 s = randi(100, 1); 4 lower = 1; 5 upper = 100; 6 7 while true 8 range = ['(' num2str(lower) ', '... num2str(upper) ')? ']; 9 x = input(range); if x > upper x < lower 12 continue; 13 end if x == s 16 disp('bingo.'); 17 break; 18 elseif x > s Zheng-Liang Lu 130 / 182
7 19 upper = x - 1; 20 else 21 lower = x + 1; 22 end if lower == upper 25 disp('gg'); 26 break; 27 end 28 end ˆ You may try nanb number guessing. Zheng-Liang Lu 131 / 182
8 Two-fold Loops ˆ Write a program which outputs the following patterns: Zheng-Liang Lu 132 / 182
9 ˆ You may use fprintf( * ) and fprintf( \n ) to print a single star and break a new line, respectively. 1 clear; clc; 2 3 % case (a) 4 for i = 1 : 5 5 for j = 1 : i 6 fprintf('*'); 7 end 8 fprintf('\n'); 9 end Zheng-Liang Lu 133 / 182
10 Exercise: Sorting 2 ˆ Let A be any array. ˆ Write a program which outputs the sorted array of A (in ascending order). ˆ For example, A = [5, 4, 1, 2, 3]. ˆ Then the sorted array is [1, 2, 3, 4, 5]. ˆ You may use sort. 2 See Zheng-Liang Lu 134 / 182
11 Practical Exercise 1 >> stocks = {'Google', 15;... 2 'Facebook', 12;... 3 'Apple', 18}; 4 >> [~, index] = sort([stocks{:, 2}], 'descend') 5 6 index = >> stocks = stocks(index, :) stocks = 'Apple' [18] 15 'Google' [15] 16 'Facebook' [12] Zheng-Liang Lu 135 / 182
12 Another Exercise: Shuffling ˆ Write a program which randomly permutes the elements of the input array A. ˆ For example, A = [1, 2, 3, 4, 5]. ˆ Then a possible permutation of A is [4, 2, 1, 3, 5]. ˆ Make sure your program correct in statistical sense. 3 ˆ Verify by Monte Carlo simulation. ˆ Write another program which enumerates all possible permutations of A. 4 3 Read 4 See salgorithm. Zheng-Liang Lu 136 / 182
13 1 >> A = 'abcdef'; 2 >> A = A(randperm(length(A))) 3 4 A = 5 6 dafbce ˆ You may use randperm(a) to generate an index array to permute the elements of A randomly. Zheng-Liang Lu 137 / 182
14 Analysis of Algorithms ˆ Given a problem, suppose that there exist various algorithms. ˆ Then we investigate these algorithms in various dimensions and choose the most appropriate one. ˆ Normally we want efficient algorithms. ˆ We now define the growth rate of the running time as a function of input size n, denoted by f (n). ˆ For simplicity, assume that every instruction takes a unit time. ˆ Can you find f (n) for each program? Zheng-Liang Lu 138 / 182
15 O-notation 5 ˆ In math, O-notation describes the limiting behavior of a function, usually in terms of simple functions. ˆ We say that f (n) O(g(n)) as n if and only if there is a constant c > 0 and a real number n 0 such that f (n) c g(n) n n 0. (1) ˆ So O(g(n)) is a collection featured by some simple function g(n). ˆ f (n) O(g(n)) means that f (n) is one instance of O(g(n)). 5 See Zheng-Liang Lu 139 / 182
16 ˆ For example, 8n 2 3n + 4 O(n 2 ). ˆ Moreover, 8n 2 3n + 4 O(n 3 ) but 8n 2 3n + 4 / O(n). Zheng-Liang Lu 140 / 182
17 Fundamental Functions for Growth Rate 6 6 See Table 4.1 and Figure 4.2 in Goodrich and etc, p Zheng-Liang Lu 141 / 182
18 ˆ We use O-notation to describe the asymptotic 7 upper bound of complexity of the algorithm. ˆ So O-notation is widely used to classify algorithms by how they respond to changes in its input size. 8 ˆ Time complexity ˆ Space complexity ˆ Note that we often make a trade-off between time and space. ˆ Unlike time, we can reuse memory. 7 The asymptotic sense is that the input size n grows toward infinity. 8 Actually, there are Θ, θ, o, Ω, and ω which are used to classify algorithms. Zheng-Liang Lu 142 / 182
19 Faster Is Better? ˆ Consider a 10-year deposit account. ˆ You deposit 10, 000 TWD in the beginning of each year. ˆ Assume that the bank pays an annual interest rate r = 10% compounded annually. ˆ Determine the balance at the end of 10 years. ˆ The answer is 175, TWD. Zheng-Liang Lu 143 / 182
20 Zheng-Liang Lu 144 / 182
21 Solution 1 1 clear; clc; 2 3 r = 0.1; 4 years = 10; 5 6 s = 1; 7 for i = 1 : years s = s * (1 + r) + 1; 9 end 10 s = s * (1 + r) * 1e4 ˆ Time complexity: O(n) ˆ Space complexity: O(1) ˆ It is similar to Horner s method. Zheng-Liang Lu 145 / 182
22 Solution 2 1 clear; clc; 2 3 r = 0.1; 4 years = 10; 5 6 s = 0; 7 for i = 1 : years 8 s = s + (1 + r) ˆ i; 9 end 10 s = s * 1e4 ˆ Time complexity: O(n) ˆ Space complexity: O(1) Zheng-Liang Lu 146 / 182
23 Solution 3 1 clear; clc; 2 3 r = 0.1; 4 years = 10; 5 s = (1 + r) * ((1 + r) ˆ years - 1) / r * 1e4 ˆ Time complexity: O(1) (Why?) ˆ Space complexity: O(1) ˆ Pros: fastest and compact; Cons: not robust Zheng-Liang Lu 147 / 182
24 Real Case: Floating Interest Rate ˆ Instead of constant interest rates, assume that the sequence of floating interest rates is r = 0.1 : 0.01 : ˆ Determine the compound amount. ˆ The balance is 125, TWD. Zheng-Liang Lu 148 / 182
25 Solution 1 clear; clc; 2 3 r = 0.1 : : 0.01; 4 years = 10; 5 6 s = 1; 7 for i = 1 : years s = s * (1 + r(i)) + 1; 9 end 10 s = s * (1 + r(end)) * 1e4 ˆ Trade-off: efficiency and generality Zheng-Liang Lu 149 / 182
26 Why Numerical Methods? ˆ Very few problems, however, have simple and analytical solutions. ˆ Numerical methods provide computational solutions for many crucial problems, thought the correctness of the numerical methods remains a big issue. 9 ˆ Simulation techniques 10 significantly reduce the cost both in industry and science. ˆ So the simulation techniques generate huge business profit. 9 See Generation_and_propagation_of_errors. 10 See Zheng-Liang Lu 150 / 182
27 All science is dominated by the idea of approximation. Bertrand Russell ( ) Essentially, all models are wrong, but some are useful. George E. P. Box ( ) Zheng-Liang Lu 151 / 182
28 Vectorization (Revisited) 11 ˆ The built-in functions such as sqrt(x) and exp(x) automatically operate on array arguments to produce an array result with the same size as the array argument x. 1 >> t = linspace(0, pi, 5); 2 >> y = sin(t) 3 4 y = More about vectorization. Zheng-Liang Lu 152 / 182
29 Advantages by Vectorization ˆ Appearance: vectorized mathematical code appears more like the mathematical expressions found in textbooks, making the code easier to understand. ˆ Less error prone: without loops, vectorized code is often shorter. ˆ Fewer lines of code mean fewer opportunities to introduce programming errors. ˆ Performance: vectorized code often runs much faster than the corresponding code containing loops. Zheng-Liang Lu 153 / 182
30 Performance Analysis In Real Time ˆ In addition to the theoretical analysis of algorithms, programmers can also use a timer to measure the performance. 12 ˆ Once you identify which functions are consuming the most time, you should determine why you are calling them, then look for alternatives to improve the overall performance. ˆ However, Amdahl s law 13 states that the speedup of a program using multiple processors in parallel computing is limited by the time needed for the sequential fraction of the program. 12 Note that the results may differ depending on the difference of run-time environments, so make sure that you benchmark the algorithms on the same conditions. 13 Amdahl (1967). Zheng-Liang Lu 154 / 182
31 Digress: Amdahl s Law ˆ Assume that a program has some codes which takes α% of total running time and can be further parallelized. ˆ Then the speedup can be achieved by investing p computers. ˆ More explicitly, Speedup = ˆ So we can calculate its limit, lim p α p α p (100 α) = + (100 α) 100 α. ˆ For example, the upper bound of speedup is 2 if α = 50. Zheng-Liang Lu 155 / 182
32 tic & toc ˆ The command tic makes a stopwatch timer start. ˆ The command toc returns the elapsed time ( 10 6 second) from the stopwatch timer started by tic. (Try.) 1 >> tic % Please wait for a second. 2 >> toc 3 4 Elapsed time is seconds. Zheng-Liang Lu 156 / 182
33 Tips for Performance 14 ˆ Preallocate arrays ˆ Repeatedly resizing arrays often requires Matlab to spend extra time looking for larger contiguous blocks of memory, and then moving the array into those blocks. ˆ Vectorize your code ˆ Create new variables if data type changes ˆ Use functions instead of scripts ˆ Avoid overloading Matlab built-in functions 14 See Techniques for Improving Performance. Zheng-Liang Lu 157 / 182
34 Example: A Benchmark 1 clear; clc; 2 3 order = 0 : 1 : 4; 4 t1 = zeros(1, length(order)); 5 t2 = zeros(1, length(order)); 6 t3 = zeros(1, length(order)); 7 8 for j = 1 : length(order) 9 num = 10 ˆ order(j); tic 12 y = []; 13 for i = 1 : num 14 y = [y, i ˆ 2]; % dynamic allocation of... array y 15 end 16 t1(j) = toc; Zheng-Liang Lu 158 / 182
35 17 18 clear y; 19 tic 20 y = zeros(1, num); % preallocation of array y 21 for i = 1 : num 22 y(i) = i ˆ 2; 23 end 24 t2(j) = toc; clear y; 27 t = 1 : 1 : num; 28 tic 29 y = t.ˆ 2; % vectorization 30 t3(j) = toc; 31 end Zheng-Liang Lu 159 / 182
36 t1 / t2 t1 / t3 t2 / t Speedup Array Size Zheng-Liang Lu 160 / 182
37 t1 / t2 t1 / t3 t2 / t3 Speedup (log scale) Array Size (log scale) Zheng-Liang Lu 161 / 182
38 All roads lead to Rome. Anonymous 但如你根本並無招式, 敵人如何來破你的招式? 風清揚 笑傲江湖 第十回 傳劍 Zheng-Liang Lu 162 / 182
39 1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 163 / 182
40 Functions ˆ The first thing of algorithm design is to divide and conquer. ˆ In other words, a large and complicated problem would be conquered by solving its subproblems. ˆ In order to reuse the algorithms without copying the codes, the best way is to make them functions. 15 ˆ The idea of the (software) functions is similar to the math function, which is typically written in form of y = f (x) with the input x and the output y. 15 Make bricks for your castle. Zheng-Liang Lu 164 / 182
41 ˆ A function is a piece of computer code that accepts an input argument from the caller, and returns output argument for the specific job the caller dealing with. ˆ Functions allow you to modularize a program by separating its tasks into self-contained units. ˆ We can program more efficiently and avoid rewriting the computer code for calculations that are performed frequently Remember that the bug propagates when you copy and paste the codes. It is a serious problem especially when you are working on a medium- or huge-level project. Zheng-Liang Lu 165 / 182
42 Arithmetic Functions Zheng-Liang Lu 166 / 182
43 Trigonometric Functions 17 ˆ Recall that 1 rad = 180 π. 17 See Table in Palm, p Zheng-Liang Lu 167 / 182
44 Rounding Functions ˆ Can you organize an algorithm for the function ceil and floor? ˆ How to check if the input is an integer? (Try.) Zheng-Liang Lu 168 / 182
45 Discrete Math Functions Zheng-Liang Lu 169 / 182
46 Max Functions Zheng-Liang Lu 170 / 182
47 ˆ The function min works in a similar way to max. Zheng-Liang Lu 171 / 182
48 Functions for Central Tendency Zheng-Liang Lu 172 / 182
49 Variance and Standard Deviation Zheng-Liang Lu 173 / 182
50 Functions for Sizes Zheng-Liang Lu 174 / 182
51 Random Number Generators ˆ You may use randi(n, m, n) to produce an m-by-n random integer matrix ranging from 1 to N. Zheng-Liang Lu 175 / 182
52 ˆ You can generate a random number sampled from a standard uniform distribution, say by a linear congruential generator. 18 ˆ Be aware that there is no true random number generator in the machines. 19 ˆ Widely used in Monte Carlo simulation 20 and random number generation of other distributions 21. ˆ Use rng( shuffle ) to generate different random sequences. 18 See 19 For now, the modern computers are all deterministic. Quantum computers share theoretical similarities with non-deterministic and probabilistic computers. 20 See Glasserman (2003). 21 See the acceptance-rejection method and Metropolis-Hastings algorithm. Zheng-Liang Lu 176 / 182
53 User-Defined Functions ˆ A user-defined function is created by 1 function [outputvar] = funcname(inputvar) 2 % comment section 3 end ˆ The output variables, if there exist, are enclosed in square brackets. ˆ The input variables, if there exist, must be enclosed with parentheses. ˆ funcname should start with a letter, and be the same as the file name in which it is saved. ˆ Before this function can be used, it must be saved into the current folder If not, change the current folder or add to the path pool. Zheng-Liang Lu 177 / 182
54 Example: Addition of Two Numbers 1 function z = myadd(x, y) 2 % input: x, y (two numbers) 3 % output: z (sum of x and y) 4 z = x + y; 5 end ˆ It seems bloody trivial. ˆ Actually, the plus sign is a kind of syntactic sugar Recall how to use an addition instruction in assembly codes. Zheng-Liang Lu 178 / 182
55 Example: Mean of A Sequence 1 function y = mymean(x) 2 % input: x (array) 3 % output: y (mean) 4 5 sum = 0; 6 n = length(x); 7 for i = 1 : n 8 sum = myadd(sum, x(i)); % call myadd 9 end 10 y = sum / n; 11 end Zheng-Liang Lu 179 / 182
56 Numbers of Arguments ˆ The variable nargin determines the number of input arguments for the function executed. ˆ Similarly, the variable nargout determines the number of output arguments from a function when executed. ˆ The variable varargin is a special word with two roles: ˆ The variable varargin declares the function with any number of arguments. 24 ˆ This variable is also a cell array containing the optional arguments to the function. ˆ The variable varargout is a special word similar to varargin but for outputs. 24 Note that varargin must be declared as the last input argument and collects all the inputs from that point onwards. Zheng-Liang Lu 180 / 182
57 Example 1 function ret = myadd(varargin) 2 switch nargin 3 case 0 4 disp('no input.'); 5 case 1 6 x = varargin{1}; 7 ret = x; 8 case 2 9 x = varargin{1}; 10 y = varargin{2}; 11 ret = x + y; 12 case 3 13 x = varargin{1}; 14 y = varargin{2}; 15 z = varargin{3}; 16 ret = x + y + z; 17 otherwise Zheng-Liang Lu 181 / 182
58 18 error('too many inputs.'); 19 end 20 end ˆ The special words nargin, nargout, varargin and varargout provide design flexibility for user-defined functions. ˆ Note that the special word varargin and varargout should be the last item in the argument list. Zheng-Liang Lu 182 / 182
ˆ Note that we often make a trade-off between time and space. ˆ Time complexity ˆ Space complexity. ˆ Unlike time, we can reuse memory.
ˆ We use O-notation to describe the asymptotic 1 upper bound of complexity of the algorithm. ˆ So O-notation is widely used to classify algorithms by how they respond to changes in its input size. 2 ˆ
More informationExercise: Sorting 1. ˆ Let A be any array. ˆ Write a program which outputs the sorted array of A (in ascending order).
Exercise: Sorting 1 ˆ Let A be any array. ˆ Write a program which outputs the sorted array of A (in ascending order). ˆ For example, A = [5, 4, 1, 2, 3]. ˆ Then the sorted array is [1, 2, 3, 4, 5]. ˆ You
More information1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225
1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225 Functions The first thing of the design of algorithms is to divide and conquer. A large and complex problem would be solved by couples
More information1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221
1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221 Functions Recall that an algorithm is a feasible solution to the specific problem. 1 A function is a piece of computer code that accepts
More informationCloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,
Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;
More informationHow to swap values of two variables without tmp? However, this naive algorithm is biased. 1
Shuffling over array elements 1... 2 for (int i = 0; i < A.length; ++i) { 3 // choose j randomly 4 int j = (int) (Math.random() A.length); 5 // swap 6 int tmp = A[i]; 7 A[i] = A[j]; 8 A[j] = tmp; 9 } 10...
More information1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174
1 class Lecture5 { 2 3 "Arrays" 4 5 } Zheng-Liang Lu Java Programming 136 / 174 Arrays An array stores a large collection of data which is of the same type. 2 // assume the size variable exists above 3
More informationCloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,
Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationNested Loops. A loop can be nested inside another loop.
Nested Loops A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started
More information1 class Lecture6 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248
1 class Lecture6 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248 All roads lead to Rome. Anonymous 但如你根本並無招式, 敵人如何來破你的招式? 風清揚,
More information1 class Lecture6 { 2 3 "Methods" // keywords: 8 return. Zheng-Liang Lu Java Programming 186 / 244
1 class Lecture6 { 2 3 "Methods" 4 5 } 6 7 // keywords: 8 return Zheng-Liang Lu Java Programming 186 / 244 Methods 2 Methods can be used to define reusable code, and organize and simplify code. The idea
More informationswitch-case Statements
switch-case Statements A switch-case structure takes actions depending on the target variable. 2 switch (target) { 3 case v1: 4 // statements 5 break; 6 case v2: 7. 8. 9 case vk: 10 // statements 11 break;
More informationExercise (Revisited)
Exercise (Revisited) Redo the cashier problem by using an infinite loop with a break statement. 1... 2 while (true) { 3 System.out.println("Enter price?"); 4 price = input.nextint(); 5 if (price
More informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
More informationArithmetic Compound Assignment Operators
Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 141 Example 1... 2 int x = 1; 3 System.out.println(x);
More informationCommon Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141
Common Errors 2 double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141 Generating random numbers Example Write a program which generates
More informationSelections. Zheng-Liang Lu 91 / 120
Selections ˆ Selection enables us to write programs that make decisions on. ˆ Selection structures contain one or more of the if, else, and elseif statements. ˆ The end statement denotes the end of selection
More informationArithmetic Compound Assignment Operators
Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 172 Example 1... 2 int x = 1; 3 System.out.println(x);
More information1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137
1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 89 / 137 Flow Controls The basic algorithm (and program) is constituted
More informationSECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB
SECTION 2: PROGRAMMING WITH MATLAB MAE 4020/5020 Numerical Methods with MATLAB 2 Functions and M Files M Files 3 Script file so called due to.m filename extension Contains a series of MATLAB commands The
More informationVariables and Assignments
Variables and Assignments ˆ A variable is used to keep a value or values. ˆ A box which contains something. ˆ In most languages, a statement looks like var = expression, where var is a variable and expression
More informationLogic is the anatomy of thought. John Locke ( ) This sentence is false.
Logic is the anatomy of thought. John Locke (1632 1704) This sentence is false. I know that I know nothing. anonymous Plato (In Apology, Plato relates that Socrates accounts for his seeming wiser than
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44
More informationEL2310 Scientific Programming
(pronobis@kth.se) Overview Overview Wrap Up More on Scripts and Functions Basic Programming Lecture 2 Lecture 3 Lecture 4 Wrap Up Last time Loading data from file: load( filename ) Graphical input and
More informationArrays. ˆ An array, is a linear data structure consisting of a collection of elements, each identified by one array index. ˆ For math, arrays could be
Arrays ˆ An array, is a linear data structure consisting of a collection of elements, each identified by one array index. ˆ For math, arrays could be ˆ row vectors: u R 1 n for any positive integer n ˆ
More informationStructure Array 1 / 50
Structure Array A structure array is a data type that groups related data using data containers called fields. Each field can contain any type of data. Access data in a structure using dot notation of
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 45
More informationIEEE Floating-Point Representation 1
IEEE Floating-Point Representation 1 x = ( 1) s M 2 E The sign s determines whether the number is negative (s = 1) or positive (s = 0). The significand M is a fractional binary number that ranges either
More informationOutline and Reading. Analysis of Algorithms 1
Outline and Reading Algorithms Running time ( 3.1) Pseudo-code ( 3.2) Counting primitive operations ( 3.4) Asymptotic notation ( 3.4.1) Asymptotic analysis ( 3.4.2) Case study ( 3.4.3) Analysis of Algorithms
More informationScope of Variables. In general, it is not a good practice to define many global variables. 1. Use global to declare x as a global variable.
Scope of Variables The variables used in function m-files are known as local variables. Any variable defined within the function exists only for the function to use. The only way a function can communicate
More informationLecture Notes for Chapter 2: Getting Started
Instant download and all chapters Instructor's Manual Introduction To Algorithms 2nd Edition Thomas H. Cormen, Clara Lee, Erica Lin https://testbankdata.com/download/instructors-manual-introduction-algorithms-2ndedition-thomas-h-cormen-clara-lee-erica-lin/
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44
More informationCS240 Fall Mike Lam, Professor. Algorithm Analysis
CS240 Fall 2014 Mike Lam, Professor Algorithm Analysis Algorithm Analysis Motivation: what and why Mathematical functions Comparative & asymptotic analysis Big-O notation ("Big-Oh" in textbook) Analyzing
More information1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133
1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 88 / 133 Flow Controls The basic algorithm (and program) is constituted
More information1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199
1 class Lecture5 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 Methods 2 Methods can be used to define reusable code, and organize
More informationLECTURE 0: Introduction and Background
1 LECTURE 0: Introduction and Background September 10, 2012 1 Computational science The role of computational science has become increasingly significant during the last few decades. It has become the
More informationAlgorithm. Algorithm Analysis. Algorithm. Algorithm. Analyzing Sorting Algorithms (Insertion Sort) Analyzing Algorithms 8/31/2017
8/3/07 Analysis Introduction to Analysis Model of Analysis Mathematical Preliminaries for Analysis Set Notation Asymptotic Analysis What is an algorithm? An algorithm is any well-defined computational
More informationData Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87
Data Types Java is a strongly-typed 1 programming language. Every variable has a type. Also, every (mathematical) expression has a type. There are two categories of data types: primitive data types, and
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44
More information21-Loops Part 2 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie
21-Loops Part 2 text: Chapter 6.4-6.6 ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie While Loop Infinite Loops Break and Continue Overview Dr. Henry Louie 2 WHILE Loop Used to
More informationAlgorithm Analysis. (Algorithm Analysis ) Data Structures and Programming Spring / 48
Algorithm Analysis (Algorithm Analysis ) Data Structures and Programming Spring 2018 1 / 48 What is an Algorithm? An algorithm is a clearly specified set of instructions to be followed to solve a problem
More informationThe return Statement
The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return
More informationVariable Scope. The variable scope is the range of the program where the variable can be referenced.
Variable Scope The variable scope is the range of the program where the variable can be referenced. Variables can be declared in class level, method level, and loop level. In general, a pair of curly brackets
More informationPseudo code of algorithms are to be read by.
Cs502 Quiz No1 Complete Solved File Pseudo code of algorithms are to be read by. People RAM Computer Compiler Approach of solving geometric problems by sweeping a line across the plane is called sweep.
More informationSankalchand Patel College of Engineering - Visnagar Department of Computer Engineering and Information Technology. Assignment
Class: V - CE Sankalchand Patel College of Engineering - Visnagar Department of Computer Engineering and Information Technology Sub: Design and Analysis of Algorithms Analysis of Algorithm: Assignment
More informationExample. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.
Example Generating random numbers Write a program which generates 2 random integers and asks the user to answer the math expression. For example, the program shows 2 + 5 =? If the user answers 7, then
More information(Refer Slide Time: 1:27)
Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture 1 Introduction to Data Structures and Algorithms Welcome to data
More informationExample. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.
Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()
More informationExample. Write a program which generates 2 random integers and asks the user to answer the math expression.
Generating random numbers Example Write a program which generates 2 random integers and asks the user to answer the math expression. For example, the program shows 2 + 5 =? If the user answers 7, then
More informationMethod Invocation. Zheng-Liang Lu Java Programming 189 / 226
Method Invocation Note that the input parameters are sort of variables declared within the method as placeholders. When calling the method, one needs to provide arguments, which must match the parameters
More informationVariables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:
Contents VARIABLES... 1 Storing Numerical Data... 2 Limits on Numerical Data... 6 Storing Character Strings... 8 Logical Variables... 9 MATLAB S BUILT-IN VARIABLES AND FUNCTIONS... 9 GETTING HELP IN MATLAB...
More informationAlgorithms and Data Structures
Algorithms and Data Structures Spring 2019 Alexis Maciel Department of Computer Science Clarkson University Copyright c 2019 Alexis Maciel ii Contents 1 Analysis of Algorithms 1 1.1 Introduction.................................
More informationIntroduction to Algorithms 6.046J/18.401J
Introduction to Algorithms 6.046J/18.401J LECTURE 1 Analysis of Algorithms Insertion sort Merge sort Prof. Charles E. Leiserson Course information 1. Staff. Prerequisites 3. Lectures 4. Recitations 5.
More informationMBI REU Matlab Tutorial
MBI REU Matlab Tutorial Lecturer: Reginald L. McGee II, Ph.D. June 8, 2017 MATLAB MATrix LABoratory MATLAB is a tool for numerical computation and visualization which allows Real & Complex Arithmetics
More informationProgramming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029
Programming Basics and Practice GEDB029 Decision Making, Branching and Looping Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029 Decision Making and Branching C language possesses such decision-making capabilities
More informationIntroduction. Like other programming languages, MATLAB has means for modifying the flow of a program
Flow control 1 Introduction Like other programming languages, MATLAB has means for modying the flow of a program All common constructs are implemented in MATLAB: for while then else switch try 2 FOR loops.
More informationAlgorithms and Data Structures
Algorithm Analysis Page 1 - Algorithm Analysis Dr. Fall 2008 Algorithm Analysis Page 2 Outline Textbook Overview Analysis of Algorithm Pseudo-Code and Primitive Operations Growth Rate and Big-Oh Notation
More informationQuestion Points Score Total 100
Name Signature General instructions: You may not ask questions during the test. If you believe that there is something wrong with a question, write down what you think the question is trying to ask and
More informationGlobal Variables. ˆ Unlike local variables, global variables are available to all functions involved.
Global Variables ˆ Unlike local variables, global variables are available to all functions involved. ˆ Use global to declare x as global. ˆ For example, the universal constant, say,. 1 ˆ However, it is
More informationControl, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control
Chapter 2 Control, Quick Overview Control Selection Selection Selection is how programs make choices, and it is the process of making choices that provides a lot of the power of computing 1 Python if statement
More informationLECTURE 1. What Is Matlab? Matlab Windows. Help
LECTURE 1 What Is Matlab? Matlab ("MATrix LABoratory") is a software package (and accompanying programming language) that simplifies many operations in numerical methods, matrix manipulation/linear algebra,
More informationData Structures and Algorithms
Berner Fachhochschule - Technik und Informatik Data Structures and Algorithms Topic 1: Algorithm Analysis Philipp Locher FS 2018 Outline Course and Textbook Overview Analysis of Algorithm Pseudo-Code and
More informationCS302 Topic: Algorithm Analysis. Thursday, Sept. 22, 2005
CS302 Topic: Algorithm Analysis Thursday, Sept. 22, 2005 Announcements Lab 3 (Stock Charts with graphical objects) is due this Friday, Sept. 23!! Lab 4 now available (Stock Reports); due Friday, Oct. 7
More informationaxiomatic semantics involving logical rules for deriving relations between preconditions and postconditions.
CS 6110 S18 Lecture 18 Denotational Semantics 1 What is Denotational Semantics? So far we have looked at operational semantics involving rules for state transitions, definitional semantics involving translations
More informationPROGRAM EFFICIENCY & COMPLEXITY ANALYSIS
Lecture 03-04 PROGRAM EFFICIENCY & COMPLEXITY ANALYSIS By: Dr. Zahoor Jan 1 ALGORITHM DEFINITION A finite set of statements that guarantees an optimal solution in finite interval of time 2 GOOD ALGORITHMS?
More informationChapter 2: Complexity Analysis
Chapter 2: Complexity Analysis Objectives Looking ahead in this chapter, we ll consider: Computational and Asymptotic Complexity Big-O Notation Properties of the Big-O Notation Ω and Θ Notations Possible
More informationAnalysis of Algorithms Part I: Analyzing a pseudo-code
Analysis of Algorithms Part I: Analyzing a pseudo-code Introduction Pseudo-code representation of an algorithm Analyzing algorithms Measuring the running time and memory size of an algorithm Calculating
More informationIntroduction to Algorithms 6.046J/18.401J/SMA5503
Introduction to Algorithms 6.046J/18.401J/SMA5503 Lecture 1 Prof. Charles E. Leiserson Welcome to Introduction to Algorithms, Fall 01 Handouts 1. Course Information. Calendar 3. Registration (MIT students
More informationDESIGN AND ANALYSIS OF ALGORITHMS. Unit 1 Chapter 4 ITERATIVE ALGORITHM DESIGN ISSUES
DESIGN AND ANALYSIS OF ALGORITHMS Unit 1 Chapter 4 ITERATIVE ALGORITHM DESIGN ISSUES http://milanvachhani.blogspot.in USE OF LOOPS As we break down algorithm into sub-algorithms, sooner or later we shall
More informationComputer Science 210 Data Structures Siena College Fall Topic Notes: Complexity and Asymptotic Analysis
Computer Science 210 Data Structures Siena College Fall 2017 Topic Notes: Complexity and Asymptotic Analysis Consider the abstract data type, the Vector or ArrayList. This structure affords us the opportunity
More informationAlgorithm Efficiency & Sorting. Algorithm efficiency Big-O notation Searching algorithms Sorting algorithms
Algorithm Efficiency & Sorting Algorithm efficiency Big-O notation Searching algorithms Sorting algorithms Overview Writing programs to solve problem consists of a large number of decisions how to represent
More informationLOOPS. Repetition using the while statement
1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while
More informationCS240 Fall Mike Lam, Professor. Algorithm Analysis
CS240 Fall 2014 Mike Lam, Professor Algorithm Analysis HW1 Grades are Posted Grades were generally good Check my comments! Come talk to me if you have any questions PA1 is Due 9/17 @ noon Web-CAT submission
More informationPART 1 PROGRAMMING WITH MATHLAB
PART 1 PROGRAMMING WITH MATHLAB Presenter: Dr. Zalilah Sharer 2018 School of Chemical and Energy Engineering Universiti Teknologi Malaysia 23 September 2018 Programming with MATHLAB MATLAB Environment
More informationUnit 1 Chapter 4 ITERATIVE ALGORITHM DESIGN ISSUES
DESIGN AND ANALYSIS OF ALGORITHMS Unit 1 Chapter 4 ITERATIVE ALGORITHM DESIGN ISSUES http://milanvachhani.blogspot.in USE OF LOOPS As we break down algorithm into sub-algorithms, sooner or later we shall
More informationLecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan
Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful
More informationLecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning
Lecture 1 Contracts 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,
More information3. Java - Language Constructs I
Names and Identifiers A program (that is, a class) needs a name public class SudokuSolver {... 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations,
More informationQuestion. Insight Through
Intro Math Problem Solving October 10 Question about Accuracy Rewrite Square Root Script as a Function Functions in MATLAB Road Trip, Restaurant Examples Writing Functions that Use Lists Functions with
More informationScanner Objects. Zheng-Liang Lu Java Programming 82 / 133
Scanner Objects It is not convenient to modify the source code and recompile it for a different radius. Reading from the console enables the program to receive an input from the user. A Scanner object
More informationLecture 2: Analyzing Algorithms: The 2-d Maxima Problem
Lecture 2: Analyzing Algorithms: The 2-d Maxima Problem (Thursday, Jan 29, 1998) Read: Chapter 1 in CLR. Analyzing Algorithms: In order to design good algorithms, we must first agree the criteria for measuring
More informationTheory and Algorithms Introduction: insertion sort, merge sort
Theory and Algorithms Introduction: insertion sort, merge sort Rafael Ramirez rafael@iua.upf.es Analysis of algorithms The theoretical study of computer-program performance and resource usage. What s also
More informationConstraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial
1 Matlab Tutorial 2 Lecture Learning Objectives Each student should be able to: Describe the Matlab desktop Explain the basic use of Matlab variables Explain the basic use of Matlab scripts Explain the
More informationEL2310 Scientific Programming
Lecture 4: Programming in Matlab Yasemin Bekiroglu (yaseminb@kth.se) Florian Pokorny(fpokorny@kth.se) Overview Overview Lecture 4: Programming in Matlab Wrap Up More on Scripts and Functions Wrap Up Last
More informationComputer Science & Engineering 150A Problem Solving Using Computers
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Stephen Scott (Adapted from Christopher M. Bourke) 1 / 41 Fall 2009 Chapter 3 3.1 Building Programs from Existing Information
More informationVectorization: An Introduction. Dr. Marco A. Arocha INGE3016-MATLAB Summer 2015
Vectorization: An Introduction Dr. Marco A. Arocha INGE3016-MATLAB Summer 2015 1 Array and Matrix Operations Operation Operator Explanation Array addition a + b array addition and matrix addition are identical
More informationPractical 4: The Integrate & Fire neuron
Practical 4: The Integrate & Fire neuron 2014 version by Mark van Rossum 2018 version by Matthias Hennig and Theoklitos Amvrosiadis 16th October 2018 1 Introduction to MATLAB basics You can start MATLAB
More informationData Structures and Algorithms CSE 465
Data Structures and Algorithms CSE 465 LECTURE 2 Analysis of Algorithms Insertion Sort Loop invariants Asymptotic analysis Sofya Raskhodnikova and Adam Smith The problem of sorting Input: sequence a 1,
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationPlotting run-time graphically. Plotting run-time graphically. CS241 Algorithmics - week 1 review. Prefix Averages - Algorithm #1
CS241 - week 1 review Special classes of algorithms: logarithmic: O(log n) linear: O(n) quadratic: O(n 2 ) polynomial: O(n k ), k 1 exponential: O(a n ), a > 1 Classifying algorithms is generally done
More information6. Control Statements II
Visibility Declaration in a block is not visible outside of the block. 6. Control Statements II Visibility, Local Variables, While Statement, Do Statement, Jump Statements main block int main () int i
More informationECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control
ECE15: Introduction to Computer Programming Using the C Language Lecture Unit 4: Flow of Control Outline of this Lecture Examples of Statements in C Conditional Statements The if-else Conditional Statement
More information3 The L oop Control Structure
3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement
More informationComputer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Functions Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 1 / 1 cbourke@cse.unl.edu Chapter 3 3.1 Building
More informationComputational complexity
Computational complexity Heuristic Algorithms Giovanni Righini University of Milan Department of Computer Science (Crema) Definitions: problems and instances A problem is a general question expressed in
More informationExercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.
Exercise Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram. Zheng-Liang Lu Java Programming 197 / 227 1... 2 int[] hist = new int[5]; 3 //
More informationAlgorithms in Systems Engineering IE172. Midterm Review. Dr. Ted Ralphs
Algorithms in Systems Engineering IE172 Midterm Review Dr. Ted Ralphs IE172 Midterm Review 1 Textbook Sections Covered on Midterm Chapters 1-5 IE172 Review: Algorithms and Programming 2 Introduction to
More information3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >:
3.4. FOR-LOOPS 65 3.4 For-loops In the previous section we looked at while-loops, Python s basic looping structure. There is a second loop construct in Python called a for-loop. This is more specialized.
More information